package main

import (
	"fmt"
	"io"
	"net"
	"sync"
	"time"
)
type Server struct{
	Ip string
	Port int
	//在线用户列表
	OnlineMap map[string]*User
	mapLock sync.RWMutex

	//消息广播的channel
	Message chan string
}

func NewServer(ip string,port int) *Server{
	server := &Server{
		Ip:ip,
		Port:port,
		OnlineMap:make(map[string]*User),
		Message:make(chan string),
	}
	return server
}
func (this *Server)BroadCast(user *User,msg string){
	sendMsg := "["+user.Addr+"]"+user.Name+":"+msg
	this.Message<-sendMsg
}
func (this *Server)ListenMessager(){
	for{
		msg := <-this.Message
		this.mapLock.Lock()
		for _,client := range this.OnlineMap{
			client.C<-msg
		}
		this.mapLock.Unlock()
	}
}
func (this* Server) Handler(conn net.Conn){
	//fmt.Println("连接建立成功")
	user := NewUser(conn,this)

	user.Online()
	//判断用户是否活跃
	isLive := make(chan bool)
	//接受客户端发送的消息
	go func(){
		buf := make([]byte,4096)
		for{
			n,err := conn.Read(buf)
			if n==0{
				//this.BroadCast(user,"下线")
				user.Offline()
				return
			}
			if err !=nil&&err != io.EOF{
				fmt.Println("Conn Read err:",err)
				return
			}
			msg := string(buf[0:n-1])
			user.Domessage(msg)
			//用户发送消息代表该用户是活跃的
			isLive<-true
		}
	}()
	//当前handler阻塞
	for{
		select{
		case <- isLive:
		case <-time.After(time.Second*100):
			//已经超时
			user.SendMsg("你被踢了")
			//销毁资源
			close(user.C)
			conn.Close()
			return
		}
	}
}
func (this *Server) Start(){
	listener,err := net.Listen("tcp",fmt.Sprintf("%s:%d",this.Ip,this.Port))
	if err!=nil{
		fmt.Println("连接建立失败，err：",err)
		return
	}
	defer listener.Close()
	go this.ListenMessager()
	for{
		conn,err := listener.Accept()
		if err!=nil{
			fmt.Println("listener accept err:",err)
			continue
		}
		go this.Handler(conn)
	}
}